package Reports;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;

/** Imprime un JComponent passe en parametre */
public class Print implements Printable {
	private Component componentToBePrinted;

	Print() {
                }
 
	public static void printComponent(TablePrintable tp, int orientation) {
		// on se cree un PrinterJob et on va chercher son PageFormat
		PrinterJob printJob = PrinterJob.getPrinterJob();
		PageFormat pageFormat = printJob.defaultPage();
		
		// orientation PageFormat.PORTRAIT ou PageFormat.LANDSCAPE
		pageFormat.setOrientation(orientation);	
		printJob.setPrintable(tp, pageFormat);
		if (printJob.printDialog()) {
			try {
				printJob.print();
			} catch(PrinterException pe) {
				System.out.println("Error printing: " + pe);
			}
		}
	}
	
	public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
		if (pageIndex > 0)
			return(NO_SUCH_PAGE);
			
		Graphics2D g2d = (Graphics2D)g;
		g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
		disableDoubleBuffering(componentToBePrinted);
		componentToBePrinted.paint(g2d);
		enableDoubleBuffering(componentToBePrinted);
		return(PAGE_EXISTS);
	}
	
	private static void disableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(false);
	}
	
	/** Re-enables double buffering globally. */
	private static void enableDoubleBuffering(Component c) {
		RepaintManager currentManager = RepaintManager.currentManager(c);
		currentManager.setDoubleBufferingEnabled(true);
	}
	

}

